package com.mondo.financialwallet.presentation.ui.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.common.ui.BaseFragment;
import com.example.common.widget.state.NetworkStateLayout;
import com.example.common.zxing.ui.CaptureActivity;
import com.mondo.financialwallet.R;
import com.mondo.financialwallet.data.DataRepository;
import com.mondo.financialwallet.data.entity.MyTokenListEntity;
import com.mondo.financialwallet.presentation.event.RequestWalletAssetEvent;
import com.mondo.financialwallet.presentation.ui.adapter.TokenListAdapter;
import com.mondo.financialwallet.presentation.model.Token;
import com.mondo.financialwallet.presentation.ui.activity.TokenAddActivity;
import com.mondo.financialwallet.presentation.ui.activity.TokenReceiptActivity;
import com.mondo.financialwallet.presentation.ui.activity.TokenDetailsActivity;
import com.mondo.financialwallet.presentation.ui.activity.TokenTransferActivity;
import com.mondo.financialwallet.presentation.utils.ActivityTitleBarHelper;
import com.mondo.financialwallet.presentation.utils.Toasts;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.Bind;
import butterknife.OnClick;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

import static android.app.Activity.RESULT_OK;
import static com.example.common.zxing.ui.CaptureActivity.INTENT_EXTRA_KEY_QR_SCAN;

public class WalletFragment extends BaseFragment implements BaseQuickAdapter.OnItemClickListener,EasyPermissions.PermissionCallbacks {


    public static Fragment newInstance() {
        return new WalletFragment();
    }

    @Bind(R.id.transfer_layout) View transferLayout;
    @Bind(R.id.scan_rq_code_image) View mScanRqCodeImage;
    @Bind(R.id.recycle_view_wallet) RecyclerView recycleViewWallet;
    @Bind(R.id.add_wallet_image) View mAddWalletImageView;
    @Bind(R.id.my_total_assets_text) TextView mMyTotalAssetsTextView;
    @Bind(R.id.token_list_state_layout) NetworkStateLayout mTokenListStateLayout;

    private TokenListAdapter mAdapter;

    @Override
    protected void setStatusBar(Activity activity) {
        ActivityTitleBarHelper.setTransparentStatus(activity);
    }

    @Override
    protected int getLayoutID() {
        return R.layout.fragment_wallet;
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Override
    protected void initActions() {
        // 列表
        mAdapter = new TokenListAdapter(R.layout.item_my_assets_token_list);
        recycleViewWallet.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);

        // 添加货币
        mAddWalletImageView.setOnClickListener(v -> TokenAddActivity.launch(v.getContext()));

        // 重新请求我的货币列表
        mTokenListStateLayout.setOnAnewRequestNetworkListener(this::requestMyTokenList);

        // 请求用户资产
        requestMyAsset();

        // 请求我的货币列表
        requestMyTokenList();
    }

    private void requestMyAsset() {
        DataRepository.get().walletAsset(result -> {
            if (result.isSuccess()) {
                mMyTotalAssetsTextView.setText(result.getDataToString());
            }
        });
    }

    private void requestMyTokenList() {
        mTokenListStateLayout.loadingNetwork();

        DataRepository.get().myTokenList(result -> {
            if (result.isSuccess()) {
                mTokenListStateLayout.successNetwork();

                List<Token> tokens = transformToken(result.getData());
                mAdapter.setNewData(tokens);
                transferLayout.setOnClickListener(v ->
                        TokenTransferActivity.launch(v.getContext(), tokens.get(0)));

                // 扫描二维码
                mScanRqCodeImage.setOnClickListener(v -> openRqCodeActivity());
            } else {
                mTokenListStateLayout.errorNetwork(result.getMsg());
            }
        });
    }

    private List<Token> transformToken(List<MyTokenListEntity.DataBean> data) {
        List<Token> tokens = new ArrayList<>();
        for (MyTokenListEntity.DataBean datum : data) {
            tokens.add(new Token(
                            datum.getLogo(),
                            datum.getToken_id(),
                            datum.getFee(),
                            datum.getTitle_en(),
                            datum.getTitle_zh(),
                            String.valueOf(datum.getUsd()),
                            String.valueOf(datum.getBalance())
                    )
            );
        }

        return tokens;
    }

    @OnClick({R.id.tv_receipt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_receipt:
                startActivity(new Intent(getContext(), TokenReceiptActivity.class));
                break;
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        TokenDetailsActivity.launch(getContext(), mAdapter.getItem(position));
    }

    @Subscribe
    public void walletAssetChangeEvent(RequestWalletAssetEvent event){
        requestMyTokenList();
        requestMyAsset();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            CaptureActivity.launch(this);
        } else if (resultCode == 0xA1 && data != null) {
            Bundle bundle = data.getExtras();
            String scanResult = Objects.requireNonNull(bundle).getString(INTENT_EXTRA_KEY_QR_SCAN);
            TokenTransferActivity.launch(getActivity(), mAdapter.getItem(0), scanResult);
        }
    }

    private void openRqCodeActivity() {
        String[] permissions = new String[]{Manifest.permission.CAMERA};
        if (!EasyPermissions.hasPermissions(getActivity(), permissions)) {
            String rationale = getString(R.string.please_approve_camera_permissions);
            EasyPermissions.requestPermissions(this, rationale, 0, permissions);
        } else {
            CaptureActivity.launch(this);
        }
    }

    @Override
    public void onRequestPermissionsResult(
            int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        CaptureActivity.launch(this);
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle(R.string.auto_authorization_failure)
                    .setRationale(R.string.please_manually_select_approve_camera_permissions).build().show();
        } else {
            Toasts.failure(R.string.authorization_failure);
        }
    }
}
